<?php

namespace Trawind\Basics\Criteria;

use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;
use Trawind\Extension\Models\Deploy\BusinessType;
use Trawind\Helpers\HttpClientHelper;

class RemoteSearchCriteria implements CriteriaInterface
{


    /**
     * @param                       $model
     * @param  RepositoryInterface  $repository
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        $remoteParam = HttpClientHelper::getRemoteParam();
        $remote = $remoteParam['remote'] ?? [];
        $where = [];

        if (!empty($remote)) {
            foreach ($remote as $business_type_id) {
                $result = BusinessType::getEloquentById($business_type_id)
                        ->getListBySearch([
                            'search' => $remoteParam['search'][$business_type_id] ?? '',
                            'searchFields' => $remoteParam['searchFields'][$business_type_id] ?? '',
                            'pageSize' => 0,
                        ])['data'] ?? [];
                $resultId = array_column($result, 'id');
                $where[] = ['business_id', 'in', $resultId];
                $where[] = ['business_type_id', '=', $business_type_id];
            }
        }
        return empty($where) ? $model : $model->where($where);
    }

}
